import {
  getTrafficOverview,
  getPopularContent,
  getUserActivity,
  getContentTraffic,
  getContentTypeStats,
  getUserGrowth,
  exportTrafficStats
} from '@/api/trafficStats'
import * as echarts from 'echarts'

export default {
  data() {
    return {
      // 日期范围
      dateRange: [],

      // 概览数据
      overviewData: {
        totalUsers: 0,
        activeUsers: 0,
        newUsers: 0,
        totalArticles: 0,
        totalTopics: 0,
        totalColumns: 0,
        totalViews: 0,
        totalLikes: 0,
        totalComments: 0,
        totalCounselors: 0,
        totalAppointments: 0,
        totalAssessments: 0,
        dailyUserStats: [],
        dailyContentStats: [],
        contentTypeStats: [],
        userGrowthStats: []
      },

      // 热门内容数据
      popularContentData: [],
      popularContentPagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },

      // 用户活跃度数据
      userActivityData: [],

      // 内容流量数据
      contentTrafficData: [],

      // 内容类型分布数据
      contentTypeStatsData: [],

      // 用户增长数据
      userGrowthData: [],

      // 图表实例
      userActivityChart: null,
      contentTrafficChart: null,
      userGrowthChart: null,
      contentTypeChart: null,

      // 流量趋势筛选器
      trafficFilters: ['views', 'likes', 'comments']
    }
  },

  methods: {
    // 初始化日期范围（默认最近30天）
    initDateRange() {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      this.dateRange = [
        this.formatDate(start),
        this.formatDate(end)
      ]
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 日期范围变化处理
    handleDateRangeChange(value) {
      this.dateRange = value
      this.refreshData()
    },

    // 刷新所有数据
    async refreshData() {
      this.loading = true
      try {
        await Promise.all([
          this.loadOverviewData(),
          this.loadPopularContentData(),
          this.loadUserActivityData(),
          this.loadContentTrafficData(),
          this.loadContentTypeStatsData(),
          this.loadUserGrowthData()
        ])
        this.$message.success('数据刷新成功')
      } catch (error) {
        this.$message.error('数据刷新失败')
      } finally {
        this.loading = false
      }
    },

    // 加载概览数据
    async loadOverviewData() {
      try {
        const dateRangeStr = this.dateRange ? this.dateRange.join(',') : ''
        const response = await getTrafficOverview(dateRangeStr)
        if (response.code === 1) {
          this.overviewData = response.data || {}
        }
      } catch (error) {
        console.error('加载概览数据失败:', error)
        this.$message.error('加载概览数据失败')
      }
    },

    // 加载热门内容数据
    async loadPopularContentData() {
      this.popularContentLoading = true
      try {
        const params = {
          page: this.popularContentPagination.page,
          pageSize: this.popularContentPagination.pageSize
        }
        const dateRangeStr = this.dateRange ? this.dateRange.join(',') : ''
        const response = await getPopularContent(params, dateRangeStr)
        if (response.code === 1) {
          this.popularContentData = response.data?.records || []
          this.popularContentPagination.total = response.data?.total || 0
        } else {
          console.warn('热门内容接口返回非成功状态:', response)
        }
      } catch (error) {
        console.error('加载热门内容数据失败:', error)
        this.$message.error('加载热门内容数据失败')
      } finally {
        this.popularContentLoading = false
      }
    },

    // 加载用户活跃度数据
    async loadUserActivityData() {
      this.userActivityLoading = true
      try {
        const dateRangeStr = this.dateRange ? this.dateRange.join(',') : ''
        const response = await getUserActivity(dateRangeStr)
        if (response.code === 1) {
          this.userActivityData = response.data || []
          // 如果页面组件有updateCharts方法，则调用
          if (this.updateCharts && typeof this.updateCharts === 'function') {
            this.$nextTick(() => {
              this.updateCharts()
            })
          }
        }
      } catch (error) {
        console.error('加载用户活跃度数据失败:', error)
        this.$message.error('加载用户活跃度数据失败')
      } finally {
        this.userActivityLoading = false
      }
    },

    // 加载内容流量数据
    async loadContentTrafficData() {
      this.contentTrafficLoading = true
      try {
        const dateRangeStr = this.dateRange ? this.dateRange.join(',') : ''
        const response = await getContentTraffic(dateRangeStr)
        if (response.code === 1) {
          this.contentTrafficData = response.data || []
          // 如果页面组件有updateCharts方法，则调用
          if (this.updateCharts && typeof this.updateCharts === 'function') {
            this.$nextTick(() => {
              this.updateCharts()
            })
          }
        }
      } catch (error) {
        console.error('加载内容流量数据失败:', error)
        this.$message.error('加载内容流量数据失败')
      } finally {
        this.contentTrafficLoading = false
      }
    },

    // 加载内容类型分布数据
    async loadContentTypeStatsData() {
      this.contentTypeStatsLoading = true
      try {
        const response = await getContentTypeStats()
        if (response.code === 1) {
          this.contentTypeStatsData = response.data || []
          // 如果页面组件有updateCharts方法，则调用
          if (this.updateCharts && typeof this.updateCharts === 'function') {
            this.$nextTick(() => {
              this.updateCharts()
            })
          }
        }
      } catch (error) {
        console.error('加载内容类型分布数据失败:', error)
        this.$message.error('加载内容类型分布数据失败')
      } finally {
        this.contentTypeStatsLoading = false
      }
    },

    // 加载用户增长数据
    async loadUserGrowthData() {
      this.userGrowthLoading = true
      try {
        const dateRangeStr = this.dateRange ? this.dateRange.join(',') : ''
        const response = await getUserGrowth(dateRangeStr)
        if (response.code === 1) {
          this.userGrowthData = response.data || []
          // 如果页面组件有updateCharts方法，则调用
          if (this.updateCharts && typeof this.updateCharts === 'function') {
            this.$nextTick(() => {
              this.updateCharts()
            })
          }
        }
      } catch (error) {
        console.error('加载用户增长数据失败:', error)
        this.$message.error('加载用户增长数据失败')
      } finally {
        this.userGrowthLoading = false
      }
    },

    // 刷新热门内容
    refreshPopularContent() {
      this.popularContentPagination.page = 1
      this.loadPopularContentData()
    },

    // 刷新用户活跃度
    refreshUserActivity() {
      this.loadUserActivityData()
    },

    // 刷新内容流量
    refreshContentTraffic() {
      this.loadContentTrafficData()
    },

    // 刷新内容类型分布
    refreshContentTypeStats() {
      this.loadContentTypeStatsData()
    },

    // 刷新用户增长
    refreshUserGrowth() {
      this.loadUserGrowthData()
    },

    // 热门内容分页大小变化
    handlePopularContentSizeChange(val) {
      this.popularContentPagination.pageSize = val
      this.popularContentPagination.page = 1
      this.loadPopularContentData()
    },

    // 热门内容当前页变化
    handlePopularContentCurrentChange(val) {
      this.popularContentPagination.page = val
      this.loadPopularContentData()
    },

    // 导出数据
    async exportData() {
      this.exportLoading = true
      try {
        const dateRangeStr = this.dateRange ? this.dateRange.join(',') : ''
        const response = await exportTrafficStats(dateRangeStr)

        // 创建下载链接
        const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `流量统计_${this.dateRange[0]}_${this.dateRange[1]}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)

        this.$message.success('数据导出成功')
      } catch (error) {
        console.error('导出数据失败:', error)
        this.$message.error('导出数据失败')
      } finally {
        this.exportLoading = false
      }
    },

    // 格式化数字
    formatNumber(num) {
      if (!num) return '0'
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },

    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '-'
      try {
        const date = new Date(dateTimeStr)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } catch (error) {
        return dateTimeStr
      }
    },

    // 获取内容类型标签
    getContentTypeTag(type) {
      const typeMap = {
        'article': { text: '文章', type: 'primary' },
        'topic': { text: '话题', type: 'success' },
        'column': { text: '专栏', type: 'warning' }
      }
      return typeMap[type] || { text: type, type: 'info' }
    },

    // ========== 图表相关方法 ==========

    // 初始化所有图表
    initCharts() {
      this.initUserActivityChart()
      this.initContentTrafficChart()
      this.initUserGrowthChart()
      this.initContentTypeChart()
    },

    // 初始化用户活跃度图表
    initUserActivityChart() {
      if (!this.$refs.userActivityChart) return

      // 如果图表实例已存在，先销毁
      if (this.userActivityChart) {
        this.userActivityChart.dispose()
      }

      this.userActivityChart = echarts.init(this.$refs.userActivityChart)
      const option = {
        title: {
          text: '用户活跃度趋势',
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['新增用户', '活跃用户', '总用户'],
          top: 40,
          textStyle: {
            fontSize: 14
          }
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '8%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.userActivityData.map(item => item.date)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '新增用户',
            type: 'line',
            data: this.userActivityData.map(item => item.newUsers),
            smooth: true,
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '活跃用户',
            type: 'line',
            data: this.userActivityData.map(item => item.activeUsers),
            smooth: true,
            itemStyle: {
              color: '#67C23A'
            }
          },
          {
            name: '总用户',
            type: 'line',
            data: this.userActivityData.map(item => item.totalUsers),
            smooth: true,
            itemStyle: {
              color: '#E6A23C'
            }
          }
        ]
      }
      this.userActivityChart.setOption(option)
    },

    // 初始化内容流量图表
    initContentTrafficChart() {
      if (!this.$refs.contentTrafficChart) return

      // 如果图表实例已存在，先销毁
      if (this.contentTrafficChart) {
        this.contentTrafficChart.dispose()
      }

      this.contentTrafficChart = echarts.init(this.$refs.contentTrafficChart)
      const option = {
        title: {
          text: '内容流量趋势',
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: this.getTrafficLegendData(),
          top: 40,
          textStyle: {
            fontSize: 14
          }
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '8%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.contentTrafficData.map(item => item.date)
        },
        yAxis: {
          type: 'value'
        },
        series: this.getTrafficSeriesData()
      }
      this.contentTrafficChart.setOption(option)
    },

    // 初始化用户增长图表
    initUserGrowthChart() {
      if (!this.$refs.userGrowthChart) return

      // 如果图表实例已存在，先销毁
      if (this.userGrowthChart) {
        this.userGrowthChart.dispose()
      }

      this.userGrowthChart = echarts.init(this.$refs.userGrowthChart)
      const option = {
        title: {
          text: '用户增长趋势',
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['新增用户', '总用户', '增长率'],
          top: 40,
          textStyle: {
            fontSize: 14
          }
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '8%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.userGrowthData.map(item => item.date)
        },
        yAxis: [
          {
            type: 'value',
            name: '用户数',
            position: 'left'
          },
          {
            type: 'value',
            name: '增长率(%)',
            position: 'right'
          }
        ],
        series: [
          {
            name: '新增用户',
            type: 'line',
            data: this.userGrowthData.map(item => item.newUsers),
            smooth: true,
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '总用户',
            type: 'line',
            data: this.userGrowthData.map(item => item.totalUsers),
            smooth: true,
            itemStyle: {
              color: '#67C23A'
            }
          },
          {
            name: '增长率',
            type: 'line',
            yAxisIndex: 1,
            data: this.userGrowthData.map(item => item.growthRate),
            smooth: true,
            itemStyle: {
              color: '#E6A23C'
            }
          }
        ]
      }
      this.userGrowthChart.setOption(option)
    },

    // 初始化内容类型分布图表
    initContentTypeChart() {
      if (!this.$refs.contentTypeChart) return

      // 如果图表实例已存在，先销毁
      if (this.contentTypeChart) {
        this.contentTypeChart.dispose()
      }

      this.contentTypeChart = echarts.init(this.$refs.contentTypeChart)
      const option = {
        title: {
          text: '内容类型分布',
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'middle',
          textStyle: {
            fontSize: 14
          },
          data: this.contentTypeStatsData.map(item => item.contentType)
        },
        series: [
          {
            name: '内容类型',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            data: this.contentTypeStatsData.map(item => ({
              value: item.count,
              name: item.contentType
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      this.contentTypeChart.setOption(option)
    },

    // 更新图表数据
    updateCharts() {
      this.$nextTick(() => {
        this.initUserActivityChart()
        this.initContentTrafficChart()
        this.initUserGrowthChart()
        this.initContentTypeChart()
      })
    },

    // 处理流量筛选器变化
    handleTrafficFilterChange(value) {
      this.trafficFilters = value
      this.initContentTrafficChart()
    },

    // 获取流量图例数据
    getTrafficLegendData() {
      const legendMap = {
        'views': '浏览量',
        'likes': '点赞数',
        'comments': '评论数'
      }
      return this.trafficFilters.map(filter => legendMap[filter])
    },

    // 获取流量系列数据
    getTrafficSeriesData() {
      const baseSeries = [
        {
          name: '浏览量',
          type: 'bar',
          data: this.contentTrafficData.map(item => item.totalViews),
          itemStyle: {
            color: '#409EFF'
          }
        },
        {
          name: '点赞数',
          type: 'bar',
          data: this.contentTrafficData.map(item => item.totalLikes),
          itemStyle: {
            color: '#67C23A'
          }
        },
        {
          name: '评论数',
          type: 'bar',
          data: this.contentTrafficData.map(item => item.totalComments),
          itemStyle: {
            color: '#E6A23C'
          }
        }
      ]

      const seriesMap = {
        'views': baseSeries[0],
        'likes': baseSeries[1],
        'comments': baseSeries[2]
      }

      return this.trafficFilters.map(filter => seriesMap[filter])
    },

    // 销毁图表实例
    destroyCharts() {
      if (this.userActivityChart) {
        this.userActivityChart.dispose()
      }
      if (this.contentTrafficChart) {
        this.contentTrafficChart.dispose()
      }
      if (this.userGrowthChart) {
        this.userGrowthChart.dispose()
      }
      if (this.contentTypeChart) {
        this.contentTypeChart.dispose()
      }
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })
  },

  beforeDestroy() {
    this.destroyCharts()
  }
}
